import 'package:ant_icons/ant_icons.dart';
import 'package:flutter_web_2021/db/TreeDB2.dart';
import 'package:flutter_web_2021/entity/bean/MenuEntity.dart';
import 'package:flutter_web_2021/entity/bean/Node.dart';
import 'package:flutter_web_2021/entity/bean/TreeHelper.dart';
import 'package:flutter_web_2021/eventbus/event.dart';
import 'package:flutter_web_2021/pages/home/HomeAppBarTabPage.dart';
import 'package:flutter_web_2021/utils/app_navigator.dart';
import 'package:rxdart/rxdart.dart';

import '../../../Include.dart';

class TreePage extends BasePage {
  static String dartPath = "lib/pages/basic/tree/TreePage.dart";

  static int id = -1;
  final HeaderItemBean headerItemBean;
  final List<MenuData> db;
  TreePage(this.headerItemBean,this.db);
  @override
  _TreePageState createState() => _TreePageState();

  @override
  String get pageName => 'TreePage';
}

class _TreePageState extends BasePageState<TreePage> {
  List nodes = [];

  var actionEventBus;

  bool isOpen = true;

  @override
  void initState() {
    getdata();
    actionEventBus = eventBus.on<TreeEvent>().listen((event) {
      this.isOpen = event.isOpen;
      setState(() {});
    });
  }

  // @override
  // void dispose() {
  //   // TODO: implement dispose
  //   super.dispose();
  //   actionEventBus?.cancel();
  // }

  void getdata() async {
    // Future<String> loadString =
    //     DefaultAssetBundle.of(context).loadString("assets/data/all_menu.json");
    // loadString.then((String value) {
    // 将参数赋予存储点击数的变量
    // Map<String, dynamic> responseData = jsonDecode(value);
    // MenuEntity userEntity = MenuEntity.fromJson(responseData);
    nodes = TreeHelper.getSortedNodes(widget.db, 1);
    nodes = TreeHelper.filterVisibleNodes(nodes);
    Log().info(nodes.toString());
    setState(() {});
    // });
  }

  List<Widget> traverseList() {
    int index = 0;
    return nodes.map((node) {
      Node nodeAs = node as Node;
      Widget view = treeItem(widget.headerItemBean,nodeAs, TreePage.id == nodeAs.id, isOpen);
      index++;
      return Column(
        children: [
          view,
          Dividers.dividerHorizontal(color: Colors.black12),
        ],
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: Colours.text_title_black,
      child: ListView(
        children: traverseList(),
      ),
    );
  }
}

class treeItem extends StatefulWidget {
  Node node;
  bool isSelect;
  bool isOpen = true;
   HeaderItemBean headerItemBean;
  treeItem(HeaderItemBean headerItemBean,Node node, bool isSelect, bool isOpen) {
    this.headerItemBean = headerItemBean;
    this.node = node;
    this.isSelect = isSelect;
    this.isOpen = isOpen;
  }

  @override
  _treeItemState createState() => _treeItemState();
}

class _treeItemState extends State<treeItem> {
  void onTreeItem(Node nodeAs) {
    TreePage.id = nodeAs.id;
    // Log().info(widget.isSelect.toString());
    if (nodeAs.isparent) {
      nodeAs.isExpand = !nodeAs.isExpand;
      setState(() {});
    } else {
      eventBus.fire(new TreeEvent(widget.headerItemBean.labelTitle,widget.isOpen));

      if(PlatformUtils.isAndroid||PlatformUtils.isIOS){
        AppNavigator.push(context,  nodeAs.view) ;
      }else{
        Log().info("目录"+widget.headerItemBean.labelTitle);


        eventBus.fire(new TabEvent(widget.headerItemBean.labelTitle,nodeAs));
      }
      // ToastUtil.showToastBottom(nodeAs.name);
    }
  }

  Widget commodityView(Node node) {
    return ListView.separated(
      padding: EdgeInsets.all(0),
      shrinkWrap: true,
      physics: new NeverScrollableScrollPhysics(),
      itemCount: node.children.length,
      scrollDirection: Axis.vertical,
      separatorBuilder: (BuildContext context, int index) {
        return Container(
          height: 0.001,
        );
      },
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
          onTap: () {
            onTreeItem(node);
          },
          child: treeItem(widget.headerItemBean,node.children[index],
              TreePage.id == node.children[index].id, widget.isOpen),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    AppUtil.instance.setContext = context;
    // TODO: implement build
    return Container(
      alignment: Alignment.centerLeft,
      width: double.infinity,
      child: Column(
        children: [
          InkWell(
            onTap: () {
              // subCustomId = nodeAs.id;
              onTreeItem(widget.node);
            },
            child: Container(
              height: 40,
              color: widget.node.isparent
                  ? Colours.text_title_black
                  : !widget.isSelect
                      ? Colours.text_sub_title_gray
                      : Colors.teal,
              child: Row(
                children: <Widget>[
                  SizedBox(
                    width: widget.isOpen
                        ? double.parse(
                            (20.0 * widget.node.getLevel()).toString())
                        : 0.0,
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  // widget.node.icon,
                  setNodeIcon(widget.node),
                  SizedBox(
                    width: widget.isOpen ? 10 : 0,
                  ),
                  Expanded(
                      child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                          Text(
                            widget.isOpen ? widget.node.name : "",
                            style: TextStyle(
                                fontSize: widget.node.isparent
                                    ? Dimens.sp14
                                    : Dimens.sp12,
                                color: Colours.bg_while),
                          ),
                      Text(
                        widget.isOpen ? widget.node.subName.toString() : "",
                        style: TextStyle(
                            fontSize:
                                widget.node.isparent ? Dimens.sp10 : Dimens.sp10,
                            color: Colors.black),
                      ),
                    ],
                  )),
                  Offstage(
                    offstage: widget.isOpen ? widget.node.isparent ? false : true :true,
                    child: InkWell(
                      onTap: () {
                        eventBus.fire(new TabEvent(widget.headerItemBean.labelTitle,widget.node));
                      },
                      child: Text(
                        "目录",
                        style: TextStyle(
                            fontSize: widget.node.isparent
                                ? Dimens.sp12
                                : Dimens.sp10,
                            color: Colours.bg_while),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: widget.isOpen ? widget.node.isparent : false,
                    child: Icon(
                      widget.node.isExpand
                          ? AntIcons.down_circle
                          : AntIcons.right_circle,
                      color: Colours.blue,
                      size: 16,
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                ],
              ),
            ),
          ),
          Offstage(
            offstage: !widget.node.isExpand,
            child: Container(
              color: Colours.text_sub_title_gray,
              child: commodityView(widget.node),
            ),
          ),
        ],
      ),
    );
  }

  ///为Node设置图标
  Widget setNodeIcon(Node n) {
    if (n.isparent && n.isExpand) {
      return n.icon = Icon(
        AntIcons.folder_open,
        color: Colours.blue,
        size: 16,
      );
    } else if (n.isparent && !n.isExpand) {
      return n.icon = Icon(
        AntIcons.folder,
        color: Colours.blue,
        size: 16,
      );
    } else {
      return n.icon = Icon(
        AntIcons.file,
        color: Colours.blue,
        size: 16,
      );
    }
  }
}
